package com.wu.util;

import com.wu.error.BusinessException;
import com.wu.error.EnumBusinessError;
import com.wu.mapper.ArticlesMapper;
import com.wu.mapper.UserLevelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-19 21:44
 */
@Component
public class MyUtil {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ArticlesMapper articlesMapper;

    @Autowired
    private UserLevelMapper userLevelMapper;

    public static String MD5(String key) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = key.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前时间（2021-11-11）
     * 返回一个格式化好的时间
     *
     * @return
     */
    public String getCurrentTime() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    public long parseTimeToString(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = null;
        try {
            d = format.parse(date);
        } catch (ParseException e) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, e.getMessage());
        }
        return d.getTime();
    }

    /**
     * 获取当前时间（2021-11-11 11:11:11）
     *
     * @return
     */
    public String getCurrentDetailedTime() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * 判断验证码是否正确
     *
     * @param phone
     * @param verification
     * @return
     */
    public boolean checkSMSIsOk(String phone, String verification) {
        String phone_ver = (String) redisUtil.get(phone);
        if (phone_ver == null) {
            return false;
        }
        return phone_ver.equalsIgnoreCase(verification);
    }


    /**
     * 判断字符串是否为数字
     *
     * @param str
     * @return
     */
    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public void checkLevel(String userId) {

        //1、先查看本人的文章数
        Integer articleCount = articlesMapper.getArticleCount(userId);
        String level;
        if (articleCount <= 5) {
            level = "码农";
        } else if (articleCount <= 10) {
            level = "码仔";
        } else if (articleCount <= 20) {
            level = "码哥";
        } else if (articleCount <= 40) {
            level = "爱码士";
        } else if (articleCount <= 60) {
            level = "码帝";
        } else if (articleCount <= 90) {
            level = "码神";
        } else {
            level = "帝";
        }
        //2、查询本人的等级
        String userLevel = userLevelMapper.getLevelByUserId(userId);
        //如果相等及不处理
        if (userLevel.equals(level)) {
            return;
        }
        //如果不相等就更新
        userLevelMapper.update(userId, level);
    }
}

